//
//  FileManagerController.swift
//  test-ios
//
//  Created by wyz5204 on 2023/4/2.
//

import UIKit

class FileManagerController: ABaseViewController {
    
    
    private let fileManeger = FileManager.default
    private let parentPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].path
    
    private lazy var label = {
        return UILabel().then { view in
            view.text = "学习IOS的文件系统"
            view.textColor = .black
        }
    }()
    private lazy var button = {
        return UIButton().then { view in
            view.setTitle("简单测试", for: UIControl.State.normal)
            view.setTitleColor(.black, for: UIControl.State.normal)
        }
    }()
    
    
    private lazy var createFolder = {
        return UIButton().then { view in
            view.setTitle("创建文件夹", for: UIControl.State.normal)
            view.setTitleColor(.black, for: UIControl.State.normal)
        }
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        label.addTo(self.view) { view in
            view.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(100)
                make.left.equalToSuperview()
            }
        }
        button.addTo(self.view) { view -> UIButton in
            view.snp.makeConstraints { make in
                make.top.equalTo(label.snp.bottom).offset(20)
                make.left.equalTo(label.snp.left)
            }
            return view
        }.rx.tap.asDriver().drive { element in
            print("onNext " , FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))
            print("onNext " , FileManager.default.urls(for: .documentationDirectory, in: .userDomainMask))
            
        } onDisposed: {
            print("onDisposed 111")
            
        }.disposed(by: self.rx.disposeBag)
        
        //--
        
        createFolder.addTo(self.view) { view -> UIButton in
            view.snp.makeConstraints { make in
                make.top.equalTo(button.snp.bottom).offset(20)
                make.left.equalTo(button.snp.left)
            }
            return view
        }.rx.tap.asDriver().drive { [weak self] element in
            self?.createFolder("wyz5204")
        } onDisposed: {
            print("onDisposed 111")
            
        }.disposed(by: self.rx.disposeBag)
        
    }
    
    //MARK: 新建文件夹
    func createFolder(_ folderName:String) -> Bool{
        
        let folderPath = parentPath + "/" + folderName
        print("开始创建" , folderPath)
        if !fileManeger.fileExists(atPath: folderPath){
            do {
                //attributes：用来设置文件夹的一些属性(只读，读写等)
                try fileManeger.createDirectory(at: URL(fileURLWithPath: folderPath), withIntermediateDirectories: true, attributes: nil)
            } catch {
                print("创建失败！")
                return false
            }
        }else{
            print("已存在")
        }
        return true
    }
    
    //MARK: 新建文件
    func createNewFile(with filePath:String ,txt:String) -> Bool{
        let txtfilePath = parentPath + "/" + filePath
        //这里以txt文本为例，也可写入其他类型文件
        let fileData = txt.data(using: String.Encoding.utf8)
        
        if !fileManeger.fileExists(atPath: txtfilePath){
            return self.writeDataToFilePath(with: txtfilePath, fileData: fileData)
        }else{
            print("已存在")
            return false
        }
    }
    //覆盖数据，推荐使用replaceItemAt(originalItemURL: URL, withItemAt: URL, backupItemName: String, options: options)
    //或replaceItemAt(originalItemURL: url, withItemAt: url)
    func recoveryFile(with filePath:String ,txt:String) -> Bool{
        let txtfilePath = parentPath + "/" + filePath
        //这里以txt文本为例，也可写入其他类型文件
        let fileData = txt.data(using: String.Encoding.utf8)
        
        if fileManeger.fileExists(atPath: txtfilePath){
            return self.writeDataToFilePath(with: txtfilePath, fileData: fileData)
        }else{
            print("文件路径不存在")
            return false
        }
    }
    
    func writeDataToFilePath(with filePath:String ,fileData:Data?) -> Bool{
        //写入数据也可以使用：fileData?.write(to: <#T##URL#>)，attributes：用来设置文件的一些属性(只读，读写等)
        return fileManeger.createFile(atPath: filePath, contents: fileData, attributes: nil)
    }
    
    //MARK: 删除文件夹
    func removeFolder(with folderName:String) -> Bool{
        
        let folderPath =  parentPath + "/" + folderName
        if fileManeger.fileExists(atPath: folderPath){
            do {
                try fileManeger.removeItem(atPath: folderPath)
            } catch {
                print("删除失败！")
                return false
            }
        }else{
            print("路径不存在")
            return false
        }
        return true
    }
    //MARK: 删除文件
    func removeFile(with filePath:String) -> Bool{
        let txtfilePath =  parentPath + "/" + filePath
        
        if fileManeger.fileExists(atPath: txtfilePath){
            do {
                try fileManeger.removeItem(atPath: txtfilePath)
            } catch {
                print("删除失败！")
                return false
            }
        }else{
            print("路径不存在")
            return false
        }
        return true
    }
    
    
    //MARK:查看文件列表
        func loadFileList(with path:String) -> [String]?{
            let folderPath =  parentPath + "/" + path
            if fileManeger.fileExists(atPath: folderPath){
                //subpathsOfDirectory(atPath: ) 可以查看完整详细的子路径 如：["test", "test/The only .txt"]
               return fileManeger.subpaths(atPath: folderPath)
            }else{
               return nil
            }
        }

        //MARK:加载文件内容
        func loadFileData(with path:String) ->Data?{
            let filePath =  parentPath + "/" + path
            if fileManeger.fileExists(atPath: filePath){
                do {
                   let fileData = try Data(contentsOf: URL(fileURLWithPath: filePath))
                    return fileData
                } catch  {
                    print("加载失败")
                    return nil
                }
            }
            print("路径不存在")
            return nil
        }
    
    
    //复制和移动，是基于两个文件路径来操作的，所以两个文件都需要存在。
       //MARK: 复制文件
       func copyFile(from oldPath:String,to newPath:String){
           let oldFilePath =  parentPath + "/" + oldPath
           let newFilePath =  parentPath + "/" + newPath
           
           if fileManeger.fileExists(atPath: oldFilePath) && fileManeger.fileExists(atPath: newFilePath){
               do {
                   try fileManeger.copyItem(atPath: oldFilePath, toPath: newFilePath)
               } catch {
                   print("文件复制失败！")
               }
           }else{
               print("文件路径不存在")
           }
           
       }
       //MARK: 移动文件
       func moveFile(from oldPath:String,to newPath:String){
           let oldFilePath =  parentPath + "/" + oldPath
           let newFilePath =  parentPath + "/" + newPath
           
           if fileManeger.fileExists(atPath: oldFilePath) && fileManeger.fileExists(atPath: newFilePath){
               do {
                   try fileManeger.moveItem(atPath: oldFilePath, toPath: newFilePath)
               } catch {
                   print("文件移动失败！")
               }
           }else{
               print("文件路径不存在")
           }
       }
}
